import { Footer } from '@/components';
import { login, getDeptList, getPostList, setUserDeptPost, getUserInfo, getresource } from '@/services/ant-design-pro/api';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
  ProFormCheckbox,
  ProForm,
} from '@ant-design/pro-components';
import { FormattedMessage, history, SelectLang, useIntl, useModel } from '@umijs/max';
import { Alert, message, Button, App, Modal, Select, Space, theme } from 'antd';
import { createStyles } from 'antd-style';
import React,{ useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import shouyebeij from '@/components/Imges/shouyebeij.jpg';
import { setToken } from '@/utils/auth';
import { log } from '@antv/g2plot/lib/utils';

// 在文件顶部添加类型定义
declare namespace API {
  type LoginParams = {
    username: string;
    password: string;
    autoLogin: boolean;
    type: string;
  };

  type LoginResult = {
    status?: string;
    type?: string;
    code?: number;
    data?: {
      access_token: string;
      expireTime: number;
      tokenType: string;
    };
    msg?: string;
  };

  type UserInfoResult = {
    code: number;
    msg: string;
    data: {
      userId: string;
      userName: string;
      realName: string;
      avatar?: string;
      roles: string[];
      permissions: string[];
      // 其他用户信息字段...
    };
  };
}

const useStyles = createStyles(({ token }) => {
  return {
    container: {
      display: 'flex',
      height: '100vh',
      backgroundImage: `url(${shouyebeij})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
    },
    content: {
      flex: 1,
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    },
    card: {
      width: '100%',
      maxWidth: '400px',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderRadius: '8px',
      padding: '30px',
      boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
    },
    header: {
      textAlign: 'center',
      marginBottom: '30px',
    },
    title: {
      fontSize: '24px',
      fontWeight: 'bold',
      color: token.colorPrimary,
      marginBottom: '10px',
    },
    subtitle: {
      fontSize: '14px',
      color: '#666',
    },
    form: {
      width: '100%',
    },
    input: {
      height: '40px',
      marginBottom: '16px',
    },
    submitButton: {
      width: '100%',
      height: '40px',
      marginTop: '20px',
      borderRadius: '4px',
    },
    footer: {
      marginTop: '20px',
      textAlign: 'center',
    },
    switchMode: {
      color: token.colorPrimary,
      cursor: 'pointer',
      '&:hover': {
        textDecoration: 'underline',
      },
    },
    modalContent: {
      padding: '24px 0',
    },
    modalTitle: {
      fontSize: '20px',
      fontWeight: 'bold',
      textAlign: 'center',
      marginBottom: '30px',
      color: token.colorPrimary,
    },
    selectGroup: {
      '& .ant-select': {
        width: '100%',
        marginBottom: '20px',

        '& .ant-select-selector': {
          height: '45px !important',
          padding: '0 20px !important',

          '& .ant-select-selection-search-input': {
            height: '45px !important',
          },

          '& .ant-select-selection-placeholder': {
            lineHeight: '45px !important',
          },

          '& .ant-select-selection-item': {
            lineHeight: '45px !important',
          },
        },
      },
    },
    modalFooter: {
      marginTop: '24px',
      display: 'flex',
      justifyContent: 'center',
      gap: '16px',
    },
    modalButton: {
      width: '120px',
      height: '40px',
      borderRadius: '20px',
    },
  };
});

const Login: React.FC = () => {
  const [isLogin, setIsLogin] = useState(true);
  const { styles } = useStyles();
  const { token } = theme.useToken();
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [deptOptions, setDeptOptions] = useState<DeptOption[]>([]);
  const [postOptions, setPostOptions] = useState<PostOption[]>([]);
  const [selectedDept, setSelectedDept] = useState<string>();
  const [selectedPost, setSelectedPost] = useState<string>();
  const [modalLoading, setModalLoading] = useState(false);
  const [routes, setRoutes] = useState<Array<{ path: string, component: React.ComponentType }>>([]);
  // 修改获取部门列表函数
  const fetchDeptList = async () => {
    try {
      const response = await getDeptList();
      console.log('修改获取部门列表函数',response);
      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item?.id,
          label: item?.departmentName,
        }));
        console.log('修改获取部门列表函数2',options);
        setDeptOptions(options);
      } else {
        message.error(response.msg || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表错误:', error);
      message.error('获取部门列表失败');
    }
  };

  // 修改获取岗位列表函数
  const fetchPostList = async (deptId: string) => {
    // 注释掉原有的接口调用
    console.log('获取岗位列表',deptId);
    try {
      const response = await getPostList({ deptId });
      if (response.code === 200 && response.data) {
        const options = response.data.map(item => ({
          value: item.id,
          label: item.positionName,
        }));
        setPostOptions(options);
      } else {
        message.error(response.msg || '获取岗位列表失败');
      }
    } catch (error) {
      console.error('获取岗位列表错误:', error);
      message.error('获取岗位列表失败');
    }

    // 使用模拟数据
  };

  // 处理部门选择变化
  const handleDeptChange = (value: string) => {
    setSelectedDept(value);
    setSelectedPost(undefined); // 清空岗位选择
    fetchPostList(value);
  };

  // 处理岗位选择变化
  const handlePostChange = (value: string) => {
    setSelectedPost(value);
  };

  // 修改确认选择函数
  const handleModalOk = async () => {
    if (!selectedDept || !selectedPost) {
      message.warning('请选择部门和岗位');
      return;
    }

    setModalLoading(true);
    try {
      const deptPostResponse = await setUserDeptPost({
        deptId: selectedDept,
        positionId: selectedPost,
      });

      if (deptPostResponse.code === 200) {
        // 获取用户信息
        const userInfoResponse = await getUserInfo();
        if (userInfoResponse.code === 200) {
          // 存储用户信息
          localStorage.setItem('user_info', JSON.stringify(userInfoResponse.data));

          // 获取资源列表
          const resourceData = await fetchResourceList();

          // 更新全局状态
          await setInitialState((s) => ({
            ...s,
            currentUser: userInfoResponse.data,
            menus: resourceData,
          }));


          setIsModalOpen(false);
          history.replace('/welcome');
          message.success('登录成功');
        }
      }
    } catch (error) {
      console.error('设置部门岗位错误:', error);
      message.error('设置失败，请重试');
    } finally {
      setModalLoading(false);
    }
  };

  // 修改登录提交函数
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values });
      console.log('msg:', msg);
      if (msg?.code === 200 && msg.data) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);

        // 保存 token
        console.log('msg.data.access_token:', msg.data.access_token);
        setToken(msg.data.access_token);

        // 获取部门列表并显示选择弹窗
        await fetchDeptList();
        setIsModalOpen(true);
        return;
      }
      // 如果失败去设置用户错误信息
      message.error(msg?.msg || '登录失败');
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };
  // const { status, type: loginType } = userLoginState;

  // 修改 status 和 loginType 的获取方式
  const { status, type: loginType } = userLoginState || {};
  const fetchResourceList = async () => {
    try {
      const response = await getresource();
      if (response.code === 200 && response.data) {
        // 直接返回后端的资源数据
        const resourceData = response.data;
        console.log('获取到的资源数据:', resourceData);
        return resourceData;
      } else {
        message.error(response.msg || '获取资源列表失败');
        return [];
      }
    } catch (error) {
      console.error('获取资源列表错误:', error);
      message.error('获取资源列表失败');
      return [];
    }
  };


  return (
    <App>
      <div className={styles.container}>
        <div className={styles.content}>
          <div className={styles.card}>
            <div className={styles.header}>
              <div className={styles.title}>
                {isLogin ? '登录账号' : '创建账号'}
              </div>
              <div className={styles.subtitle}>
                {isLogin ? '立即登录已有账号开始探索' : '加入我们，一起加油！'}
              </div>
            </div>

            <ProForm
              submitter={false}
              onFinish={async (values) => {
                if (isLogin) {
                  await handleSubmit(values as API.LoginParams);
                } else {
                  // 处理注册逻辑
                  console.log('注册:', values);
                }
              }}
              className={styles.form}
            >
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                  className: styles.input,
                }}
                placeholder="请输入用户名"
                rules={[{ required: true, message: "请输入用户名" }]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                  className: styles.input,
                }}
                placeholder="请输入密码"
                rules={[{ required: true, message: "请输入密码" }]}
              />

              <Button
                type="primary"
                htmlType="submit"
                className={styles.submitButton}
              >
                {isLogin ? '登录' : '注册'}
              </Button>
            </ProForm>

            <div className={styles.footer}>
              <span>
                {isLogin ? '还未注册?' : '已有账号?'}
                <a
                  className={styles.switchMode}
                  onClick={() => setIsLogin(!isLogin)}
                >
                  {isLogin ? '注册' : '登录'}
                </a>
              </span>
            </div>
          </div>
        </div>

        {/* 部门岗位选择弹窗保持不变 */}
        <Modal
          title={null}
          open={isModalOpen}
          onOk={handleModalOk}
          onCancel={() => setIsModalOpen(false)}
          footer={null}
          width={400}
          maskClosable={false}
          closable={false}
          centered
          className={styles.modalContent}
        >
          <div className={styles.modalTitle}>
            选择您的部门和岗位
          </div>

          <div className={styles.selectGroup}>
            <Select
              placeholder="请选择部门"
              options={deptOptions}
              value={selectedDept}
              onChange={handleDeptChange}
              size="large"
              style={{ marginBottom: 20 }}
            />
            <Select
              placeholder="请选择岗位"
              options={postOptions}
              value={selectedPost}
              onChange={handlePostChange}
              disabled={!selectedDept}
              size="large"
            />
          </div>

          <div className={styles.modalFooter}>
            <Button
              className={styles.modalButton}
              onClick={() => setIsModalOpen(false)}
            >
              取消
            </Button>
            <Button
              type="primary"
              className={styles.modalButton}
              onClick={handleModalOk}
              loading={modalLoading}
            >
              确认
            </Button>
          </div>
        </Modal>
      </div>
    </App>
  );
};

export default Login;
